<template>
    <div class="employees-container">
        <el-card>
            <template #header>
                <div class="card-header">
                    <div class="header-left">
                        <el-icon class="header-icon">
                            <UserFilled />
                        </el-icon>
                        <span>员工管理</span>
                    </div>
                    <el-button type="primary" @click="handleAdd">
                        <el-icon><Plus /></el-icon>新增员工
                    </el-button>
                </div>
            </template>

            <el-table 
                :data="employeeList" 
                style="width: 100%" 
                v-loading="loading"
                :header-cell-style="{
                    background: '#f5f7fa',
                    color: '#606266',
                    fontWeight: 500
                }"
            >
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="avatar" label="头像" width="80">
                    <template #default="{ row }">
                        <el-avatar :size="40" :src="row.avatar">
                            {{ row.nickname?.charAt(0)?.toUpperCase() }}
                        </el-avatar>
                    </template>
                </el-table-column>
                <el-table-column prop="username" label="用户名" />
                <el-table-column prop="nickname" label="昵称" />
                <el-table-column prop="phone" label="手机号" />
                <el-table-column prop="email" label="邮箱" />
                <el-table-column prop="role" label="角色" align="center" width="120">
                    <template #default="{ row }">
                        <el-tag :type="row.role === '超级管理员' ? 'danger' : 'primary'">
                            {{ row.role }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" align="center" width="100">
                    <template #default="{ row }">
                        <el-switch
                            v-model="row.status"
                            :active-value="1"
                            :inactive-value="0"
                            @change="handleStatusChange(row)"
                        />
                    </template>
                </el-table-column>
                <el-table-column prop="createdTime" label="创建时间" align="center">
                    <template #default="{ row }">
                        {{ formatDateTime(row.createdTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" link @click="handleEdit(row)">
                            <el-icon><Edit /></el-icon>编辑
                        </el-button>
                        <el-button type="danger" link @click="handleDelete(row)">
                            <el-icon><Delete /></el-icon>删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 新增/编辑对话框 -->
        <el-dialog
            :title="dialogType === 'add' ? '新增员工' : '编辑员工'"
            v-model="dialogVisible"
            width="500px"
        >
            <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="form.username" :disabled="dialogType === 'edit'" />
                </el-form-item>
                <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="form.nickname" />
                </el-form-item>
                <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
                    <el-input v-model="form.password" type="password" show-password />
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="form.phone" />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email" />
                </el-form-item>
                <el-form-item label="角色" prop="role">
                    <el-select v-model="form.role">
                        <el-option label="超级管理员" value="超级管理员" />
                        <el-option label="普通员工" value="普通员工" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="submitting">
                    确定
                </el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Plus, Edit, Delete, UserFilled } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

const loading = ref(false)
const employeeList = ref([])
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const submitting = ref(false)

const form = ref({
    username: '',
    nickname: '',
    password: '',
    phone: '',
    email: '',
    role: '普通员工'
})

const rules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    phone: [
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    email: [
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ]
}

// 获取员工列表
const getEmployeeList = async () => {
    loading.value = true
    try {
        const res = await request({
            url: '/employee/list',
            method: 'get'
        })
        employeeList.value = res.data
        console.log(employeeList.value)
    } catch (error) {
        console.error('获取员工列表失败:', error)
    } finally {
        loading.value = false
    }
}

// 新增员工
const handleAdd = () => {
    dialogType.value = 'add'
    form.value = {
        username: '',
        nickname: '',
        password: '',
        phone: '',
        email: '',
        role: '普通员工'
    }
    dialogVisible.value = true
}

// 编辑员工
const handleEdit = (row) => {
    dialogType.value = 'edit'
    form.value = { ...row }
    dialogVisible.value = true
}

// 删除员工
const handleDelete = (row) => {
    ElMessageBox.confirm('确认删除该员工吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await request({
                url: `/employee/${row.id}`,
                method: 'delete'
            })
            ElMessage.success('删除成功')
            getEmployeeList()
        } catch (error) {
            console.error('删除失败:', error)
        }
    })
}

// 修改状态
const handleStatusChange = async (row) => {
    try {
        await request({
            url: '/employee/status',
            method: 'put',
            data: {
                id: row.id,
                status: row.status
            }
        })
        ElMessage.success('状态修改成功')
    } catch (error) {
        console.error('状态修改失败:', error)
        row.status = row.status === 1 ? 0 : 1 // 恢复状态
    }
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return

    try {
        await formRef.value.validate()
        submitting.value = true

        const url = dialogType.value === 'add' ? '/employee/add' : '/employee/update'
        await request({
            url,
            method: dialogType.value === 'add' ? 'post' : 'put',
            data: form.value
        })

        ElMessage.success(`${dialogType.value === 'add' ? '新增' : '编辑'}成功`)
        dialogVisible.value = false
        getEmployeeList()
    } catch (error) {
        console.error('提交失败:', error)
    } finally {
        submitting.value = false
    }
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
    if (!dateTime) return ''
    const date = new Date(dateTime)
    return date.toLocaleString()
}

onMounted(() => {
    getEmployeeList()
})
</script>

<style scoped>
.employees-container {
    padding: 20px;
    height: 100%;
}

.el-card {
    height: 100%;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-left {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 16px;
    font-weight: 500;
}

.header-icon {
    font-size: 18px;
    color: #409EFF;
}

:deep(.el-avatar) {
    background: #409EFF;
}

:deep(.el-tag) {
    text-transform: capitalize;
}

:deep(.el-dialog__body) {
    padding-top: 20px;
}
</style> 